package ac.beiwo.baas.file.handler.impl;

import ac.beiwo.baas.common.entity.SimpleCode;
import ac.beiwo.baas.common.entity.SimpleError;
import ac.beiwo.baas.file.entity.BaasFile;
import ac.beiwo.baas.file.handler.IFileHandler;
import ac.beiwo.baas.file.service.FileService;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created by Staryet on 15/8/27.
 */
@Component
public class QiniuFileHandler implements IFileHandler {

    @Autowired
    private FileService fileService;

    @Value("${host}")
    private String host;
    @Value("${qiniu.ak}")
    private String ak;
    @Value("${qiniu.sk}")
    private String sk;
    @Value("${qiniu.bucket}")
    private String bucket;
    @Value("${qiniu.file.host}")
    private String qiniuHost;

    @Override
    public Map<String, Object> getToken(String name) {
        Auth auth = Auth.create(ak, sk);
        //随机生成的文件名
        String fileName = UUID.randomUUID().toString().replace("-", "");
        //生成上传策略
        StringMap policy = new StringMap();
        policy.put("callbackUrl", host);
        policy.put("callbackBody", "platform=qiniu&name=$(fname)&source=" + name);
        String token = auth.uploadToken(bucket, fileName, 60000, policy);
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("name", fileName);
        return result;
    }

    @Override
    public BaasFile callback(String body, HttpServletRequest request) throws SimpleError {
        //云存储回调 处理BaasFile的存储
        Auth auth = Auth.create(ak, sk);
        boolean isValid = auth.isValidCallback(request.getHeader("Authorization"), request.getRequestURL().toString(), body.getBytes(), request.getContentType());
        if (!isValid) {
            //授权失败 无效请求
            throw new SimpleError(SimpleCode.FILE_CALLBACK_NO_VALID);
        }
        //获取参数
        Map<String, String> params = getparams(body);
        BaasFile file = new BaasFile();
        file.setName(params.get("source"));
        file.setKey(params.get("name"));
        file.setUrl(qiniuHost + file.getKey());
        fileService.saveFile(file);
        return file;
    }

    private Map<String, String> getparams(String body) {
        Map<String, String> params = new HashMap<>();
        String[] p = body.split("&");
        for (String param : p) {
            String[] kv = param.split("=");
            String name = kv[0];
            String value = kv[1];
            params.put(name, value);
        }
        return params;
    }

}
